<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>NETTY SOCKET.IO DEMO</title>
    <base>

    <script src="js/socket.io/socket.io.js"></script>
    <script src="js/moment.min.js"></script>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <style>
        body {
            padding: 20px;
        }

        #console {
            height: 450px;
            overflow: auto;
        }

        .username-msg {
            color: orange;
        }

        .connect-msg {
            color: green;
        }

        .disconnect-msg {
            color: red;
        }

        .user {
            color: crimson;
        }
    </style>
</head>

<body>
<div id="console" class="well"></div>
<div><input type="text" id="message-input">
    <button type="button" onclick="say()">发送</button>
</div>
</body>
<script type="text/javascript">
    var socket;
    connect();

    function connect() {

        socket = io.connect('http://localhost:9099/test', {
            transports: ['websocket', 'xhr-polling', 'jsonp-polling'], query: {
                username: "Jack"
            }
        });

        socket.on('connect', function (data) {
            console.log('链接成功');
            console.log(data);

            var now = '<span style="color: cadetblue">' + moment().format('YYYY-MM-dd HH:mm:ss') + '</span>';

            serverOutput('<span class="connect-msg">' + now + ' Jack 上线了</span>');
        });
        socket.on('push', function (data) {
            var now = '<span style="color: cadetblue">' + moment().format('YYYY-MM-dd HH:mm:ss') + '</span>';
            output('<span class="username-msg">' + now + " <span class='user'>" + data.from + "对" + data.to + "说:</span> " + data.payload + ' </span>');
            console.log(data);
        });

        socket.on('disconnect', function () {
            var now = '<span style="color: cadetblue">' + moment().format('YYYY-MM-dd HH:mm:ss') + '</span>';
            serverOutput('<span class="disconnect-msg">' + now + ' Jack 下线了 </span>');
        });
    }

    function say() {
        socket.emit("push", {from: "jack", to: "lucy", payload: "client  jack message"})
        alert("success")
    }

    function output(message) {
        var element = $("<div>" + " " + message + "</div>");
        $('#console').prepend(element);
    }

    function serverOutput(message) {
        var element = $("<div>" + message + "</div>");
        $('#console').prepend(element);
    }
</script>
</html>
